package com.ringtheweb.web.action;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.async.Asynchronous;
import org.jboss.seam.annotations.async.Expiration;
import org.jboss.seam.annotations.async.FinalExpiration;
import org.jboss.seam.annotations.async.IntervalDuration;
import org.jboss.seam.async.QuartzTriggerHandle;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.faces.Renderer;
import org.jboss.seam.log.Log;

import com.ringtheweb.common.util.ThrowableUtils;
import com.ringtheweb.model.RoleType;
import com.ringtheweb.model.User;
import com.ringtheweb.model.notification.RegistrationQueryNotification;
import com.ringtheweb.persistence.dao.INotificationDAO;
import com.ringtheweb.persistence.dao.IUserDAO;

@Name("mailNotificationAction")
@Scope(ScopeType.APPLICATION)
public class MailNotificationAction {
	
    @In QuartzTriggerHandle timer;

    @In("#{notificationDAO}")INotificationDAO notificationDAO;
    
    @In("#{userDAO}") IUserDAO userDAO;
    
	@In(create=true)Renderer renderer;
	
    @Logger Log logger;

    @Asynchronous
    public QuartzTriggerHandle scheduleSendApprovalMailsForUser(@Expiration Date when, 
                                 @IntervalDuration Long interval,
                                 @FinalExpiration Date endDate)  { 
		try {
	    	logger.info("Checking for notifications to send...");
			
	    	List<RegistrationQueryNotification> emailNotifications = notificationDAO.findRegistrationQueriesWithMaxCount(3);
	    	
	    	for (RegistrationQueryNotification registrationQueryNotification : emailNotifications) {
	    		
	    		User userToRegister = registrationQueryNotification.getUserToRegister();
	    		Date currentDate = Calendar.getInstance().getTime();
	    		
	    		// If at least one administrator is warned, it is considered as a success
	    		boolean sentSucceeded = false;
	        	for(User adminUser: userDAO.findByRoleName(RoleType.ADMIN.name())) {
	        		logger.info("Sending notification for user #0 to #1 ", userToRegister.getEmail(), 
	        				adminUser.getEmail());
	        		try {
	        			Contexts.getEventContext().set("userToRegister", userToRegister);
	        			Contexts.getEventContext().set("adminUser", adminUser);
	        			renderer.render("/email/adminApproval.xhtml");
	        			sentSucceeded = true;
	        		}
	        		catch(Throwable t) {
	        			logger.error("An error occured while sending email",t );
	        			registrationQueryNotification.getHistoryLines().put(currentDate,
	        					ThrowableUtils.stackTraceAsString(t));
	        		}
	        		
	        	}
	        	if (sentSucceeded) {
	        		registrationQueryNotification
	        			.getHistoryLines().put(currentDate, "Registration sent to one of administrators");
	        		registrationQueryNotification.setStatus(true);
	        	}
	        	
	        	notificationDAO.makePersistent(registrationQueryNotification);
	        	
	    	}
	        return timer;
			
		}
		catch(Throwable t) {
			logger.error("An error occured dealing with notification query",t );
			return null;
		}
    	
    }
}
